YAHOO.namespace('springmole');

(function () {

    var Event = YAHOO.util.Event, 
		Dom = YAHOO.util.Dom,
		
		ROOT_CLASS = 'table-panel', 
		DATASOURCE_URL = 'databasetable.spy', 
		
		DEFAULT_CONFIG = {
        	TABLE_XML_CONFIG: 'tableXmlConfig'
		};
    
    
    function getYUIColumnFromSQLType(sqlType) {
        switch (sqlType) {
        case 2003: // ARRAY
        case 2001: // DISTINCT
        case 70: // DATALINK
        case 2000: // JAVA_OBJECT
        case 0: // NULL
        case 1111: // OTHER
        case 2006: // REF
        case 2002: // STRUCT
            return {
                formatter: 'textarea',
                parser: 'string'
            };
            
        case 16: // BOOLEAN
        case -7: // BIT
            return {
                formatter: 'text',
                parser: 'string'
            };
            
        case -2: // BINARY 	
        case 2004: // BLOB 	
        case 2005: // CLOB 	
            return '';
            
        case 92: // TIME
        case 93: // TIMESTAMP
        case 91: // DATE
            return {
                formatter: function (elCell, oRecord, oColumn, oData) {
                    try {
                        var oDate = oData;
                        elCell.innerHTML = oDate.toString('yyyy-MM-dd HH:mm:ss');
                    } 
                    catch (e) {
                        elCell.innerHTML = 'Parse error';
                    }
                },
                parser: function (data) {
                    try {
                        return Date.parseExact(data, 'yyyy-MM-ddTHH:mm:ss');
                    } 
                    catch (e) {
                        return false;
                    }
                }
            };
            
        case 3: // DECIMAL
        case -5: // BIGINT				
        case 8: // DOUBLE
        case 6: // FLOAT
        case 4: // INTEGER
        case -6: // TINYINT
        case 7: // REAL
        case 2: // NUMERIC
        case 5: // SMALLINT
            return {
                formatter: 'number',
                parser: 'number'
            };
            
        case 1: // CHAR																					
        case 12: // VARCHAR
            return {
                formatter: 'text',
                parser: 'string'
            };
            
        case -4: // LONGVARBINARY
        case -1: // LONGVARCHAR
        case -3: // VARBINARY
            return {
                formatter: 'textarea',
                parser: 'string'
            };
        }
    }
    
    
    function createDataTable(tableId, tableData, tableConfig) {
        var columnConfigArray = [], dataSourceFieldArray = [], columnIndex, column, yuiColumn, clolumnName, dataSource;
        
        for (columnIndex = 0; columnIndex < tableData.childNodes.length; columnIndex++) {
            column = tableData.childNodes[columnIndex];
            yuiColumn = getYUIColumnFromSQLType(parseInt(column.getAttribute('sqlType'), 10));
            clolumnName = column.getAttribute('name');
            
            columnConfigArray.push({
                key: clolumnName,
                label: clolumnName,
                formatter: yuiColumn.formatter,
                sortable: true
            });
            
            dataSourceFieldArray.push({
                key: clolumnName,
                parser: yuiColumn.parser,
                locator: '@' + clolumnName
            });
        }
        		
        dataSource = new YAHOO.util.DataSource(DATASOURCE_URL);
        dataSource.connMethodPost = true;
		//dataSource.connMgr
        dataSource.responseType = YAHOO.util.DataSource.TYPE_XML;
        dataSource.useXPath = true;
        dataSource.responseSchema = {
            resultNode: 'Row',
            fields: dataSourceFieldArray,
            metaFields: {
                totalRecords: '//ResultData/@total'
            }
        };
        
		//function fnCallback(e) { alert("request Event"); }
		//dataSource.subscribe('requestEvent', fnCallback, this, true);

        return new YAHOO.widget.ScrollingDataTable(tableId, columnConfigArray, dataSource, tableConfig);
    }
    
    
    
    
    /**
     *
     * @param {Object} el
     * @param {Object} userConfig
     */
    YAHOO.springmole.TablePanel = function (el, userConfig) {
        YAHOO.springmole.TablePanel.superclass.constructor.call(this, el, userConfig);
        
        Dom.addClass(this.innerElement, ROOT_CLASS);
    };
    
    
    YAHOO.lang.extend(YAHOO.springmole.TablePanel, YAHOO.springmole.SQLDataPanel, {
    
        _oDataTable: null,
        
        
        initDefaultConfig: function () {
            YAHOO.springmole.TablePanel.superclass.initDefaultConfig.call(this);
            
            this.cfg.addProperty(DEFAULT_CONFIG.TABLE_XML_CONFIG, {});
        },
        
        
        init: function (el, userConfig) {
            YAHOO.springmole.TablePanel.superclass.init.call(this, el, userConfig);
            
        },
        
        
        render: function (parentNode) {
            YAHOO.springmole.TablePanel.superclass.render.call(this, parentNode);
            
            var connection = this.cfg.getProperty(this.CONFIG.CONNECTION.key),
            	tableXmlConfig = this.cfg.getProperty(DEFAULT_CONFIG.TABLE_XML_CONFIG),
            	tableName = tableXmlConfig.getAttribute('name'),
            	
            	dataTableId = Dom.generateId(),
            	toolbarId = Dom.generateId();
            
            this.setHeader("Table: " + tableXmlConfig.getAttribute('name'));
            this.setBody('<div id="' + toolbarId + '" class="' + this.TOOL_BAR_BUTTON_CLASS + '"></div><div id="' + dataTableId + '"></div>');
            
            
            function formatRequest(p_sSort, p_sOrder, p_nIndex, p_nSize) {
                return "sortField=" + p_sSort +
	            	'&sortOrder=' + p_sOrder +
	            	"&rowIndex=" + p_nIndex +
	            	"&pageSize=" + (p_nIndex + p_nSize - 1) +
	            	'&query=SELECT * FROM ' + tableName +
	            	'&url=' + connection.url +
	            	'&userName=' + connection.userName +
	            	'&password=' + connection.password;            	
            }
            
            
            function requestBuilder(p_oState, p_oDataTable) {
                // Get states or use defaults
                p_oState = p_oState ||
                {
                    pagination: null,
                    sortedBy: null
                };
            	
            	var sort = (p_oState.sortedBy) ? p_oState.sortedBy.key : 'id',
                	dir = (p_oState.sortedBy && p_oState.sortedBy.dir === YAHOO.widget.DataTable.CLASS_DESC) ? 'desc' : 'asc',
                	startIndex = (p_oState.pagination) ? p_oState.pagination.recordOffset : 0,
                	results = (p_oState.pagination) ? p_oState.pagination.rowsPerPage : 100;
                
                return formatRequest(sort, dir, startIndex, results);
            }
            
            
            function getInitialRequest() {
            	// TODO: get first column in datasource and default page size in paginator
            	return formatRequest('id', 'asc', 0, 25);
            }
            
            
            Event.onContentReady(this.id, function () {
            	var oButtonRefresh,
					oButtonExport;

                oButtonRefresh = new YAHOO.widget.Button({
                    type: "button",
                    label: "Refresh",
                    height: 50,
                    container: toolbarId
                });
                
                oButtonExport = new YAHOO.widget.Button({
                    type: "menu",
                    label: "Options",
                    height: 50,
                    container: toolbarId,
                    menu: [
						{text: 'Test Option 1', value: '1'},
						{text: 'Test Option 2', value: '2'},
						{text: 'Test Option 3', value: '3'}
					]
                });
                
                this._oDataTable = createDataTable(dataTableId, tableXmlConfig, {
                    dynamicData: true,
                    width: 200 + 'px',
                    height: 100 + 'px',
                    draggableColumns: true,
                    paginator: this._paginator,
                    generateRequest: requestBuilder,
                    initialRequest: getInitialRequest()
                });
                
                this._oDataTable.handleDataReturnPayload = function (oRequest, oResponse, oPayload) {
                    oPayload.totalRecords = oResponse.meta.totalRecords;
                    return oPayload;
                };
                
                this._oDataTable.set('height', 200 + 'px');
                this._oDataTable.set('width', 550 + 'px');
            }, this, true);
            
            this._panelResize.on('resize', function (args) {
            	this._oDataTable.set('height', (args.height - (this.header.clientHeight + this.footer.clientHeight + 75)) + 'px');
            	this._oDataTable.set('width', (args.width - 23) + 'px');
            }, this, true);
            
        } // render
        
    });
    
}());
